package com.sample.generator.demo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.sample.generator.controller.GeneratorController;

/**
 * Hello world!
 * 
 */
public class App {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		if (args.length < 1) {
			System.err.println("TODO length must > 1");
			System.err.println("Usage: TODO");
			System.exit(0);
		}

		try {
			new App().start(args);
			System.exit(0);
		} catch (Exception e) {
			// TODO Logging
			e.printStackTrace();
			System.exit(1);
		}
	}

	@SuppressWarnings("unchecked")
	public void start(String[] args) throws Exception {

		List<String> contextPaths = new ArrayList<String>(Arrays.asList(args));

		String userLocalContextPath = getUserLocalContextPath();
		if (userLocalContextPath != null) {
			contextPaths.add(userLocalContextPath);
		}

		ApplicationContext context = new FileSystemXmlApplicationContext(
				contextPaths.toArray(new String[contextPaths.size()]));

		Map<String, GeneratorController> controllerMap = (Map<String, GeneratorController>) context
				.getBeansOfType(GeneratorController.class);
		for (GeneratorController controller : controllerMap.values()) {
			controller.execute();
		}
	}

	private static String getUserLocalContextPath() throws IOException {

		String homePath = System.getProperty("user.home");
		if (homePath == null) {
			return null;
		}
		File userLocalContextFile = new File(homePath, "generationContext.xml");
		if (userLocalContextFile.exists() && userLocalContextFile.isFile()) {
			return userLocalContextFile.getCanonicalPath();
		}
		return null;
	}
}
